package cn.fangline.camerademo02;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

public class PlaneView extends View {
    // 定义水平仪仪表盘图片
    public Bitmap back;
    // 定义水平仪中的气泡图标
    public Bitmap bubble;
    // 定义水平仪中气泡 的X、Y座标
    public float bubbleX, bubbleY;

    private int width;

    private int height;

    private int backWidth;
    private int backHeight;

    public int maxScreenW, maxSreenH;

	public static Bitmap drawableToBitmap(Drawable drawable) {
		// 取 drawable 的长宽
		int w = drawable.getIntrinsicWidth();
		int h = drawable.getIntrinsicHeight();

		// 取 drawable 的颜色格式
		Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
				: Bitmap.Config.RGB_565;
		// 建立对应 bitmap
		Bitmap bitmap = Bitmap.createBitmap(w, h, config);
		// 建立对应 bitmap 的画布
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, w, h);
		// 把 drawable 内容画到画布中
		drawable.draw(canvas);
		return bitmap;
	}


    public PlaneView(Context context, AttributeSet attrs) {
        super(context, attrs);

		// 获取窗口管理器
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		// 获取屏幕的宽度和高度
		Display display = wm.getDefaultDisplay();
		DisplayMetrics metrics = new DisplayMetrics();
		display.getMetrics(metrics);
		width = metrics.widthPixels;
		height = metrics.heightPixels;

        // 加载水平仪图片和气泡图片
		Drawable bubbleDrawable = context.getResources().getDrawable(R.drawable.oval);
		bubble = drawableToBitmap(bubbleDrawable);
		Log.i("tag", bubble.toString());

		maxScreenW = width - bubble.getWidth();
		maxSreenH = height - bubble.getHeight();

		Drawable backDrawable = context.getResources().getDrawable(R.drawable.vector_drawable_calibrator);
		back = drawableToBitmap(backDrawable);
		backWidth = back.getWidth();
		backHeight = back.getHeight();
//		Toast.makeText(context,"backWidth is"+backWidth+"backHeight"+backHeight,Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 绘制水平仪表盘图片

        canvas.drawBitmap(back, (width - backWidth)/2, (height - backHeight)/2, null);
        // 根据气泡座标绘制气泡
        canvas.drawBitmap(bubble, bubbleX, bubbleY, null);
    }
}
